package cn.kgc.springmvc.day03.handler;

import cn.kgc.springmvc.day03.entity.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/5/7
 * @description  非法请求拦截
 *     preHandle   boolean
 *      true    放行
 *      false  不允许访问   请求到此结束
 */
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String servletPath = request.getServletPath();
        System.out.println("servletPath = " + servletPath);
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if (ObjectUtils.isEmpty(user)){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ResponseResult responseResult = new ResponseResult().setCode(403).setMessage("请认证后访问");
            // jackson  ObjectMapper    java  -> String json
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(responseResult);
            writer.write(s);
            writer.close();
            return  false;
        }
        return true;
    }
}
